<template>
  <div class="start-node">
    <el-form label-position="top" label-width="80px" ref="nodeForm" :rules="rules" :model="formData">
      <el-form-item v-if="productType === 'cloud'" label="执行方式" prop="executeMethod">
        <el-select v-model="formData.executeMethod">
          <el-option
            v-for="item in executionModesList"
            :key="item.key"
            :label="item.value"
            :value="item.key">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="执行间隔" v-if="formData.executeMethod === 'signal'" prop="interval">
        <el-select v-model="formData.intervalType" @change="intervalTypeChange">
          <el-option
            v-for="item in intervalList"
            :key="item.key"
            :label="item.name"
            :value="item.key">
          </el-option>
        </el-select>
        <div class="interval-custom" v-if="formData.intervalType === 'custom'">
          <el-input-number v-model="formData.interval" :controls='false' class="input-number" :min="1" :max="99"></el-input-number>
          <span class="second-suffix">秒</span>
        </div>
      </el-form-item>
      <el-form-item label="执行条件" v-if="formData.executeMethod === 'event'" prop="executeEvent">
        <el-select v-model="formData.executeEvent">
          <el-option
            v-for="item in eventList"
            :key="item.value"
            :label="item.name"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <template v-if="formData.executeMethod === 'period'">
        <el-form-item label="时间类型" prop="periodData.periodType">
          <el-select v-model="formData.periodData.periodType" @change="periodTypeChange">
            <el-option
              v-for="item in timeTypeList"
              :key="item.key"
              :label="item.name"
              :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 每天重复 -->
        <el-form-item label="执行时间" v-if="formData.periodData.periodType === 'day'" class="is-required">
          <el-col class="mb-8" v-for="(item, index) in formData.periodData.executeTime" :key="item.key">
            <el-col :span="22">
              <el-form-item
                :prop="'periodData.executeTime.' + index + '.time'"
                :rules="{
                    validator: validateExecuteTime,
                    trigger: ['change', 'blur']
                  }"
                >
                <el-time-picker
                  class='custom-picker'
                  :clearable='false'
                  prefix-icon='el-icon-date'
                  v-model="item.time"
                  format="HH:mm"
                  value-format="HH:mm:00"
                  style="width:100%">
                </el-time-picker>
              </el-form-item>
            </el-col>
            <el-col :span="2" class="text-right">
              <svg-icon icon-class="删除" className="signal-open" @click="deleteTime(index)"/>
            </el-col>
          </el-col>
          <el-button v-if="formData.periodData.executeTime.length < maxTimeCount" type="text" class="font-14" @click="addTime">
            <i class="el-icon-circle-plus"></i>
            添加执行时间
          </el-button>
        </el-form-item>
        <!-- 每周重复 -->
        <template v-if="formData.periodData.periodType === 'week'">
          <el-form-item prop="periodData.periodWeekdays">
            <el-select v-model="formData.periodData.periodWeekdays" multiple popper-class="period-weeks-popper" placeholder="请选择需要重复的星期">
              <el-option
                v-for="item in weekList"
                :key="item.key"
                :label="item.name"
                :value="item.key">
                <div><el-checkbox :value="formData.periodData.periodWeekdays.includes(item.key)" disabled class="check-week">{{ item.name }}</el-checkbox></div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="执行时间" class="is-required">
            <el-col class="mb-8" v-for="(item, index) in formData.periodData.executeTime" :key="item.key">
              <el-col :span="22">
                <el-form-item
                  :prop="'periodData.executeTime.' + index + '.time'"
                  :rules="{
                      validator: validateExecuteTime,
                      trigger: ['change', 'blur']
                    }"
                  >
                  <el-time-picker
                    class='custom-picker'
                    :clearable='false'
                    prefix-icon='el-icon-date'
                    v-model="item.time"
                    format="HH:mm"
                    value-format="HH:mm:00"
                    style="width:100%">
                  </el-time-picker>
                </el-form-item>
              </el-col>
              <el-col :span="2" class="text-right">
                <svg-icon icon-class="删除" className="signal-open" @click="deleteTime(index)"/>
              </el-col>
            </el-col>
            <el-button v-if="formData.periodData.executeTime.length < maxTimeCount" type="text" class="font-14" @click="addTime">
              <i class="el-icon-circle-plus"></i>
              添加执行时间
            </el-button>
          </el-form-item>
        </template>
        <!-- 自定义重复 -->
        <el-form-item v-if="formData.periodData.periodType === 'custom'">
          <el-col :span="18">
            <el-form-item prop="periodData.periodFrequency">
              <el-input-number
                v-model="formData.periodData.periodFrequency"
                :max="99"
                :min="1"
                :controls="false"
                class="input-number-left"
                style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-select v-model="formData.periodData.periodUnit">
              <el-option
                v-for="item in timeUnit"
                :key="item.key"
                :label="item.name"
                :value="item.key">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <!-- 指定时间 -->
        <el-form-item label="执行时间" v-if="formData.periodData.periodType === 'fixedTime'" class="is-required">
          <el-col class="mb-8" v-for="(item, index) in formData.periodData.executeTime" :key="item.key">
            <el-col :span="22">
              <el-form-item
                :prop="'periodData.executeTime.' + index + '.time'"
                :rules="{
                    validator: validateExecuteTime,
                    trigger: ['change', 'blur']
                  }"
                >
                <el-date-picker
                  class='custom-picker'
                  :clearable='false'
                  prefix-icon='el-icon-date'
                  v-model="item.time"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptions"
                  style="width:100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="2" class="text-right">
              <svg-icon icon-class="删除" className="signal-open" @click="deleteTime(index)"/>
            </el-col>
          </el-col>
          <el-button v-if="formData.periodData.executeTime.length < maxTimeCount" type="text" class="font-14" @click="addTime">
            <i class="el-icon-circle-plus"></i>
            添加执行时间
          </el-button>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import jsUtil from '@/utils/helper/jsUtil'
import RuleNodeBaseClass from '@/components/ruleNode/RuleNodeBaseClass'
import RuleNodeApi from '@/api/ruleNode/startNode'
import { executionModesList, timeType, timeWeek, timeUnit, intervalType, intervalValueMap } from './startNode.model'

export default {
  name: 'ExternalNodeStartNode',
  mixins: [RuleNodeBaseClass],
  data() {
    return {
      formData: {
        executeMethod: null,
        executeEvent: null,
        intervalType: null,
        interval: null,
        periodData: {
          periodType: null,
          periodFrequency: '1',
          periodUnit: 'minute',
          periodWeekdays: [],
          executeTime: [{
            time: null
          }]
        }
      },
      eventList: [],
      intervalList: intervalType,
      timeTypeList: timeType,
      weekList: timeWeek,
      timeUnit: timeUnit,
      maxTimeCount: 10,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      rules: {
        executeMethod: [{
          required: true, message: '执行方式不能为空', trigger: 'change'
        }],
        executeEvent: [{
          required: true, message: '执行条件不能为空', trigger: 'change'
        }],
        interval: [{
          required: true, message: '执行间隔不能为空', trigger: 'blur'
        }, {
          required: true, message: '执行间隔不能为空', trigger: 'change'
        }],
        'periodData.periodType': [{
          required: true, message: '时间类型不能为空', trigger: 'change'
        }],
        'periodData.periodFrequency': [{
          required: true, message: '重复周期不能为空', trigger: 'blur'
        }],
        'periodData.periodWeekdays': [{
          required: true, message: '重复周期不能为空', trigger: 'change'
        }]
      }
    }
  },
  computed: {
    productType() {
      return this.$store.state.product.type
    },
    executionModesList() {
      return executionModesList.filter(el => el.scope.includes(this.productType))
    }
  },
  watch: {
    'formData.executeMethod'() {
      this.$nextTick(() => this.clearValidate())
    },
    'formData.periodData.periodType'() {
      this.$nextTick(() => this.clearValidate())
    }
  },
  mounted() {
    this.initValue()
    this.$nextTick(() => {
      this.formData.executeMethod = this.productType === 'vehicle' ? 'signal' : (this.formData.executeMethod || null)
    })
    RuleNodeApi.getTspEventList().then(res => {
      this.eventList = res.data
    })
  },
  methods: {
    initValue() {
      const initFormData = jsUtil.deepClone(this.initialForm)
      Object.assign(this.formData, initFormData)
    },
    deleteTime(index) {
      if (this.formData.periodData.executeTime.length > 1) {
        this.formData.periodData.executeTime.splice(index, 1)
      }
      this.$nextTick(() => this.$refs.nodeForm.validate())
    },
    addTime() {
      this.formData.periodData.executeTime.push({
        key: new Date().getTime(),
        time: ''
      })
    },
    addFixTime() {
      this.fixTime.push({
        key: new Date().getTime(),
        time: ''
      })
    },
    clearValidate() {
      this.$refs.nodeForm.clearValidate()
    },
    validateExecuteTime(rule, value, callback) {
      if (!value || (value && value === '')) {
        callback(new Error('重复周期不能为空'))
      } else {
        const executeTimeList = this.formData.periodData.executeTime
        const duplicateItem = executeTimeList.filter((el, index) => {
          if (el.time.constructor === String) {
            return el.time === value
          } else if (el.time.constructor === Date) {
            return el.time.getTime() === value.getTime()
          }
          return false
        })
        if (duplicateItem.length > 1) {
          callback(new Error('时间不能重复'))
        } else {
          const _nowTime = new Date().getTime()// 当前时间
          const _configData = new Date(value).getTime() // 所选值毫秒数
          if (_configData < _nowTime) {
            callback(new Error('执行时间不能小于当前时间'))
          } else {
            callback()
          }
          // this.$refs.nodeForm.validateField('periodData.executeTime')
          callback()
        }
      }
    },
    // 注意，不能通过watch进行重置，否则加载已有表单时也会重置
    periodTypeChange() {
      this.formData.periodData.executeTime = [{
        time: null
      }]
    },
    intervalTypeChange(val) {
      if (val === 'custom') {
        this.formData.interval = null
      } else {
        this.formData.interval = intervalValueMap[this.formData.intervalType]
      }
    },
    getFormData() {
      return jsUtil.deepClone(this.formData)
    },
    validateForm() {
      let isValid = true
      this.$refs.nodeForm.validate(valid => { (!valid) && (isValid = false) })
      return isValid
    }
  }
}
</script>

<style lang="scss" scoped>
.start-node {
  .interval-custom {
    display: flex;
    .input-number{
      flex-shrink: 0;
      width: 100%;
      margin: 8px 0;
      margin-right: -14px;
    }
    .second-suffix{
      color: #000;
      line-height: 48px;
      transform:translateX(-8px);
    }
    ::v-deep.el-input-number .el-input__inner {
      text-align: left;
    }
  }
}
</style>
<style lang="scss">
.start-node {
  .custom-picker{
    .el-input__prefix{
      left: auto;
      right: 4px;
      color: #1f1f1f;
    }
    .el-input__inner{
      padding-left: 10px;
    }
  }
}
.period-weeks-popper{
  .check-week{
    .el-checkbox__input.is-disabled {
      .el-checkbox__inner{
        background-color: #fff;
        border-color: #e0e0e0;
        cursor: pointer;
        &::after{
          border-color: #fff;
        }
      }
      & + span.el-checkbox__label{
        color: #1f1f1f;
        cursor: pointer;
      }
      &.is-checked{
        .el-checkbox__inner{
          background-color: #486cff;
          border-color: #486cff;
        }
      }
    }
  }
}
</style>
